<template>
  <div class="my-file-upload">
    <el-upload
      ref="uploadRef"
      v-loading="loading"
      :accept="fileTypes"
      :action="`${baseUrl}${apiUrl}`"
      :auto-upload="true"
      :before-upload="handleBeforeUpload"
      :data="uploadData"
      :headers="{ Authorization: token }"
      :multiple="false"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :show-file-list="false"
    >
      <div class="upload-body">
        <div class="el-upload__text">
          <el-image class="w-32px h-30px mt-10px" :src="iconFile">
            <template #placeholder></template>
          </el-image>
          <span>{{ text }}</span>
        </div>
      </div>
    </el-upload>
    <vab-draggable v-show="fileLists.length > 0" v-bind="dragOptions" item-key="{ element }" :list="fileLists">
      <template #item="{ element: item, index }">
        <div class="file-list-item">
          <div class="file-name-box">{{ item.name }}</div>
          <div class="file-down-but" @click.stop="handleDownload(item.url)">
            <download />
          </div>
          <div class="file-del-but" @click.stop="handleDelete(index)">
            <close-bold />
          </div>
        </div>
      </template>
    </vab-draggable>

    <div class="el-upload__tip">
      <vab-icon icon="information-2-line" style="font-size: 12px; color: #e6a23c" />
      <em>单次上传1个文件,且单个文件不超过{{ fileMax }}MB</em>
      <!-- 修改: 更新提示信息 -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { CloseBold, Download } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { ElUpload } from 'element-plus'
import VabDraggable from 'vuedraggable'
import iconFile from '/@/assets/icon_images/file.png'
import { handleDownload } from '/@/utils/download'

import { useUserStore } from '/@/store/modules/user'
const $baseMessage = inject<any>('$baseMessage')
const userStore = useUserStore()
const token = userStore.getToken
const baseUrl = ref(import.meta.env.VITE_APP_BASE_URL)
const ossUrl = ref(import.meta.env.VITE_OSS_BASE_URL)
const apiUrl = ref('/api/ossPut')

const loading = ref<any>(false)
const uploadRef = ref<InstanceType<typeof ElUpload>>()
const fileMax = ref<any>(5)

const uploadData = ref<any>({
  // activityId: '',type: '',
})

const dragOptions = computed(() => {
  return { animation: 600, group: 'description' }
})

const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: { type: [Array, String], default: '' }, // 修改: 支持字符串或数组
  text: { type: String, default: '点击上传附件' }, // 显示文案
  fileTypes: { type: String, default: 'image/*' }, // 文件类型限制
})
interface FileItem {
  url: string
  name?: string
}
const fileLists: any = computed({
  get: () => {
    if (Array.isArray(props.modelValue)) {
      return props.modelValue.length > 0 ? [props.modelValue[0]] : []
    } else if (typeof props.modelValue === 'string') {
      return props.modelValue ? [{ url: props.modelValue, name: props.modelValue.split('/').at(-1) || '-' }] : []
    }
    return []
  },
  set: (val: FileItem[]) => {
    if (Array.isArray(val) && val.length > 0) {
      emit('update:modelValue', val[0].url)
    } else {
      emit('update:modelValue', '')
    }
  },
})

const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile.type)
  // const isCorrectType = rawFile.type === props.fileTypes || props.fileTypes === 'image/*'
  const isLt20M = rawFile.size! / 1024 / 1024 < fileMax.value
  // if (!isCorrectType) $baseMessage(`上传文件类型必须是 ${props.fileTypes}!`, 'error', 'vab-hey-message-error')
  if (isLt20M) {
    loading.value = true
  } else {
    $baseMessage(`上传文件大小不能超过 ${fileMax.value}MB!`, 'error', 'vab-hey-message-error')
  }
  console.log('File before upload:', rawFile) // 增加调试打印
  return isLt20M
}

const handleExceed: UploadProps['onExceed'] = () => {
  $baseMessage('最多只能上传1个文件!', 'error', 'vab-hey-message-error') // 修改: 更新提示信息
  console.log('File upload exceeded limit') // 增加调试打印
}

// 上传失败
const handleError: UploadProps['onError'] = (err) => {
  $baseMessage(JSON.parse(err.message ?? '{}')?.message, 'error', 'vab-hey-message-error')
  loading.value = false // 重置 loading 状态
  console.log('File upload error:', err) // 增加调试打印
}

// 上传成功
const handleSuccess: UploadProps['onSuccess'] = (res) => {
  loading.value = false
  if (res && res.status === 200) {
    const obj = {
      id: res.name,
      name: res.name?.split('/').at(-1) || '-',
      url: `${ossUrl.value}/${res.name}`,
    }
    fileLists.value = [obj] // 修改: 只保留一个文件
    $baseMessage('上传成功', 'success', 'vab-hey-message-success')
    console.log('File upload success:', res) // 增加调试打印
  } else {
    $baseMessage('上传失败', 'error', 'vab-hey-message-error')
    console.log('File upload failed:', res) // 增加调试打印
  }
}

// 删除文件
const handleDelete = () => {
  fileLists.value = [] // 修改: 清空文件列表
  console.log('File deleted') // 增加调试打印
}

// 添加: handleRemove 方法
const handleRemove: UploadProps['onRemove'] = () => {
  fileLists.value = [] // 修改: 清空文件列表
  console.log('File removed') // 增加调试打印
}

// 添加: handlePreview 方法
const handlePreview: UploadProps['onPreview'] = (file) => {
  window.open(file.url, '_blank')
  console.log('File preview:', file) // 增加调试打印
}

const handleSubmit = () => {
  uploadRef.value?.submit()
}

// 初始化 赋值
const handleInit = (initList?: any) => {
  if (Array.isArray(initList) && initList.length > 0) {
    fileLists.value = [initList[0]]
  } else if (typeof initList === 'string') {
    fileLists.value = [{ url: initList, name: initList.split('/').at(-1) || '-' }]
  } else {
    fileLists.value = []
  }
  console.log('File init:', fileLists.value) // 增加调试打印
}

// 关闭 清空数据
const handleClose = () => {
  fileLists.value = [] // 修改: 清空文件列表
  uploadRef.value!.clearFiles()
  console.log('File close and clear') // 增加调试打印
}
</script>

<style lang="scss">
.my-file-upload {
  .upload-body {
    padding: 0 20px;
    width: 220px;
    height: 126px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #fafcff;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 1px;
    border-radius: 5px;
    border: 1px dashed#D3E3FD;
    box-shadow:
      1px 1px 1px #f2f6fc,
      -1px -1px 1px #ebeef5;
    -webkit-transition: all 0.6s;
    -moz-transition: all 0.6s;
    transition: all 0.6s;
  }
  .upload-body:hover {
    border: 1px dashed#4e88f3;
  }
  .el-upload__text {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 13px;
    color: #666666;
  }
  .el-upload__tip {
    font-size: 11px;
    letter-spacing: 1px;
  }
  .file-list-item {
    position: relative;
    margin-top: 6px;
    padding: 0 10px;
    width: 330px;
    height: 34px;
    background: #fafcff;
    border-radius: 3px;
    border: 1px dashed #d3e3fd;
    cursor: move;
    box-shadow:
      1px 1px 1px #f2f6fc,
      -1px -1px 1px #ebeef5;
    -webkit-transition: all 0.4s;
    -moz-transition: all 0.4s;
    transition: all 0.4s;
    color: #666666;

    .file-name-box {
      width: 260px;
      font-size: 13px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .file-down-but {
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      top: 5px;
      right: 34px;
      width: 22px;
      height: 22px;
      padding: 3px;
      cursor: pointer;
    }
    .file-del-but {
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      top: 5px;
      right: 6px;
      width: 22px;
      height: 22px;
      padding: 4px;
      cursor: pointer;
    }
  }
  .file-list-item:hover {
    color: #4e88f3;
    border: 1px dashed#4e88f3;
  }
}
</style>
